package com.wbao.dianniu.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.QaDataChangeManager;
import com.wbao.dianniu.manager.QuestGoodManager;
import com.wbao.dianniu.manager.ShareSDKManager;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

public class QAInfoAdapter extends BaseAdapter  {
	private Context mContext;
	private List<QaResponse> mList;
	private LayoutInflater mInflater;
	private GridHolder holder;
	//是否有热门置顶显示
	private int topCounts = 0;

	public QAInfoAdapter(Context ctx) {
		mContext = ctx;
		mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mList = new ArrayList<QaResponse>();
	}

	/**
	 * 清空数据
	 * @param list
	 */
	public void cleanData(){
		if(null != mList){
			mList.clear();
		}
		topCounts = 0;
	}
	
	public void addDataList(List<QaResponse> list){
		if(null == mList){
			mList = new ArrayList<QaResponse>();
		}
		for (int i = 0; i < list.size(); i++) {
			mList.add(list.get(i));
		}
	}
	
	public void setData(List<QaResponse> list){
		if(null == mList){
			mList = new ArrayList<QaResponse>();
		}
		mList = list;
	}
	
	public List<QaResponse> getList(){
		if(null == mList){
			mList = new ArrayList<QaResponse>();
		}
		return mList;
	}
	
	/**
	 * 数据是否置顶显示处理方法，主要处理是否置顶文字的显示和置顶与非置顶之间的分割线显示
	 */
	public void processList(){
		topCounts = 0;
		for (int i = 0; i < mList.size(); i++) {
			if(1 == mList.get(i).top){
				topCounts ++ ;
			}
		}
		if(topCounts > 0){
			mList.get(0).isTopShow = 1;
			mList.get(topCounts -1).isLineShow = 1;
		}
	}
	
	@Override
	public int getCount() {
		if (null == mList)
			return 0;
		else
			return mList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int index, View convertView, ViewGroup parent) {
		holder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.qa_list_item, null);   
			holder = new GridHolder();
			holder.isTopTV = (TextView) convertView.findViewById(R.id.isTop_show);
			holder.isTopLine = (View) convertView.findViewById(R.id.isTop_line);
			holder.underLine = (View) convertView.findViewById(R.id.under_line);
			holder.headIV = (ImageView)convertView.findViewById(R.id.qa_head_iv);
			holder.nameTV =  (TextView)convertView.findViewById(R.id.qa_name_tv);
			holder.labelTV =  (TextView)convertView.findViewById(R.id.qa_label_tv);
			holder.contentTV = (TextView) convertView.findViewById(R.id.qa_content_tv);
			holder.praiseTV = (TextView) convertView.findViewById(R.id.qa_praise_tv);
			holder.praiseIV = (ImageView) convertView.findViewById(R.id.qa_praise_iv);
			holder.commentTV = (TextView) convertView.findViewById(R.id.qa_comment_tv);
			holder.headInfoLayout = (LinearLayout) convertView.findViewById(R.id.headInfoLayout);
			holder.praiseLayout = (LinearLayout) convertView.findViewById(R.id.praiseLayout);
			holder.shareLayout = (LinearLayout) convertView.findViewById(R.id.shareLayout);
			holder.responseLayout = (LinearLayout) convertView.findViewById(R.id.responseLayout);
			 holder.gridview = (CanDoBlankGridView) convertView.findViewById(R.id.noScroollGridView);
			convertView.setTag(holder); 
		}else{
			 holder = (GridHolder) convertView.getTag();   
		}
		final QaResponse resp = mList.get(index);
		if(null != resp){
			PictureDownloadUtils.displayHeadImage(mContext,holder.headIV, resp.headPic);
			holder.nameTV.setText(resp.realName==null ? "":resp.realName);
			holder.labelTV.setText(resp.label ==null ? "":resp.label );
			holder.contentTV.setText(resp.content);
			if (1 == resp.isTopShow) {
				holder.isTopTV.setVisibility(View.VISIBLE);
			} else {
				holder.isTopTV.setVisibility(View.GONE);
			}
			if (1 == resp.isLineShow) {
				holder.isTopLine.setVisibility(View.VISIBLE);
				holder.underLine.setVisibility(View.GONE);
			} else {
				holder.isTopLine.setVisibility(View.GONE);
				holder.underLine.setVisibility(View.VISIBLE);
			}
			//是否点赞
			if(0 == resp.isGood){
				holder.praiseIV.setImageResource(R.drawable.click_praise_icon_nor);
			}else{
				holder.praiseIV.setImageResource(R.drawable.click_praise_icon_sel);
			}
			Utils.showPriseCounts(resp.goodCount, holder.praiseTV);
			Utils.showPriseCounts(resp.answerCount, holder.commentTV);
			
			DetailListener dListener = new DetailListener(resp);
			//添加监听事件
			holder.headIV.setOnClickListener(dListener);
			holder.headInfoLayout.setOnClickListener(dListener);
			holder.contentTV.setOnClickListener(dListener);
			holder.shareLayout.setOnClickListener(new ShareListener(resp));
			holder.responseLayout.setOnClickListener(dListener);
			holder.praiseLayout.setOnClickListener(new praiseListener(index, resp.isGood, resp.goodCount));
			if(TextUtils.isEmpty(resp.questImgs)){
				  holder.gridview.setVisibility(View.GONE); // 没有图片资源就隐藏GridView
	        } else {
	        	ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
	        	holder.gridview.setVisibility(View.VISIBLE);
	        	//通过图片张数 设置gridview的高度 
	        	double multiple = Math.ceil((float)imageUrls.size()/GlobalContext.NUMCOLUMNS);
	        	int height = (int) (Utils.dip2px(mContext, 80) * multiple + (multiple -1) * Utils.dip2px(mContext, 10));
	        	int width = 0;
	        	if(multiple >= 1){
	        		width = Utils.dip2px(mContext, 80) * GlobalContext.NUMCOLUMNS + (GlobalContext.NUMCOLUMNS -1) * Utils.dip2px(mContext, 5);
	        	}else{
	        		width = Utils.dip2px(mContext, 80) * imageUrls.size() + (imageUrls.size()  -1) * Utils.dip2px(mContext, 5);
	        	}
	        	width = width + Utils.dip2px(mContext, 10);// 加上pendingLeft 10dp
	        	LinearLayout.LayoutParams lp = new LayoutParams(width, height);
	        	holder.gridview.setLayoutParams(lp);
	            holder.gridview.setAdapter(new NoScrollGridAdapter(mContext, imageUrls));
	            // 点击回帖九宫格，查看大图
	            holder.gridview.setOnItemClickListener(new MyItemClickListener(imageUrls));
	            holder.gridview.setOnTouchInvalidPositionListener(new CanDoBlankGridView.OnTouchInvalidPositionListener() {

	                @Override
	                public boolean onTouchInvalidPosition(int motionEvent) {
	                /*当返回false的时候代表交由父级控件处理，当return true的时候表示你已经处理了该事件并不让该事件再往上传递。为了出发listview的item点击就得返回false了*/
	                    return false;
	                }
	            });
	        }
		}
		
		return convertView;
	}
 
	class MyItemClickListener implements OnItemClickListener{

		private ArrayList<String> url;
		public MyItemClickListener(ArrayList<String> url) {
			this.url = url;
		}
		
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			//弹出图片查看按钮
            imageBrower(position, url);
		}
		
	} 
	
	
	/**
     * 打开图片查看器
     * 
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(mContext, position, urls2);
    }
 
	
   /**
    * 点赞
 * @author yejianjun
 *
 */
class praiseListener implements OnClickListener{
	   private int isGood;
		private int goodCount;
		private int position;
	   public praiseListener(int position,int isGood,int goodCount) {
		   this.position = position;
		   this.isGood = isGood;
		   this.goodCount = goodCount;
	}
	@Override
		public void onClick(View v) {
			if (v.getId() == R.id.praiseLayout) {
				if(isGood == 0){
					isGood = 1;
					goodCount++;
				}else{
					isGood = 0;
					goodCount--;
				}
				goodclick(mList.get(position).id);
				QaDataChangeManager.getInstance().priseNotify(mList.get(position).id, isGood, goodCount);
			}
		}

	}
	
	private void goodclick(int questId){
		QuestGoodManager manager = new QuestGoodManager(mContext);
		manager.good(GlobalContext.accountId, questId);
		// 通知界面点赞数变更  notifyQaChanged(questId,isGood);
		
	}
	
	/**
	 * 分享
	 */
	private class ShareListener implements OnClickListener{

		private QaResponse resp;
		
		public ShareListener(QaResponse resp) {
			this.resp = resp;
		}
		
		@Override
		public void onClick(View v) {
			System.out.println("点击了分享");
			String imageUrl = null;
			if(TextUtils.isEmpty(resp.questImgs)){
				imageUrl =  GlobalContext.cdndownUrl +  resp.headPic;
			}else{
				ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
				imageUrl = imageUrls.get(0);
			}
			ShareSDKManager.getInstance().showShare(mContext, resp.content, 1, imageUrl, resp.id);
		}
		
	}
	
	/**
	 *	问题详情、点击头像、点击点赞。点击回复等
	 *
	 */
	private class DetailListener implements OnClickListener{
		private QaResponse resp;
		public DetailListener(QaResponse resp) {
			this.resp = resp;
		}
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.qa_content_tv:
			case R.id.responseLayout:
				Utils.intoQaDetailActivity(mContext, resp);
				break;
			case R.id.qa_head_iv:
			case R.id.headInfoLayout:
			case R.id.qa_add_friend_btn:
				Utils.intoHeadInfoActivity(resp.accountId, mContext);
				break;
			default:
				break;
			}
		}
		
	}
	
	public class GridHolder {
		/**	热门置顶	*/
		private TextView isTopTV;
		/**	热门置顶下划线	*/
		private View isTopLine;
		/**	under划线	*/
		private View underLine;
		/** 头像 */
		private ImageView headIV;
		/** 昵称 */
		public TextView nameTV;
		/** 标签 */
		private TextView labelTV;
		/** 内容 */
		public TextView contentTV;
		/** 点赞数 */
		public TextView praiseTV;
		/** 点赞图标 */
		public ImageView praiseIV;
		/** 回复数 */
		public TextView commentTV;
		/** 名字，标签 */
		private LinearLayout headInfoLayout;
		/** 分享按钮*/
		private LinearLayout shareLayout;
		/** 点赞按钮 */
		private LinearLayout praiseLayout;
		/** 回复按钮 */
		private LinearLayout responseLayout;
		/**	图片显示	*/
		private CanDoBlankGridView  gridview;
	}
	
	public void addOneQuestData(QaResponse addData) {
		if (null != mList) {
			mList.add(topCounts, addData);
			notifyDataSetChanged();
		}
	}

	public void removeOneData(int id) {
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == id){
				mList.remove(i);
				notifyDataSetChanged();
				break;
			}
		}
	}

	public void priseNotify(int questId, int isGood, int goodCounts) {
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == questId){
				mList.get(i).isGood = isGood;
				mList.get(i).goodCount = goodCounts;
				notifyDataSetChanged();
				break;
			}
		}
	}

	public void replyNotify(int questId, int answerCounts) {
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == questId){
				mList.get(i).answerCount = answerCounts;
				notifyDataSetChanged();
				break;
			}
		}
	}

}
